#include "widget.h"
#include "ui_widget.h"

#include<QDebug>
#include<QMessageBox>
#include<QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器");
    socket=new QUdpSocket(this);
    //连接信号槽
    connect(socket,&QUdpSocket::readyRead,this,&Widget::processRequest);
    //绑定端口
    bool ret=socket->bind(QHostAddress::Any,8080);
    if(!ret)
    {
        QMessageBox::critical(this,"绑定窗口失败",socket->errorString());
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    //1.读取请求并解析
   const QNetworkDatagram& requestDatagram=socket->receiveDatagram();
   QString request=requestDatagram.data();
   //2.根据请求计算响应
   const QString& response=process(request);
    //3.把响应回到客户端
   //构建初始化
   QNetworkDatagram responseDatagram(response.toUtf8(),requestDatagram.senderAddress(),requestDatagram.senderPort());
   socket->writeDatagram(responseDatagram);

   //写log日志
   QString log="["+requestDatagram.senderAddress().toString()+":"+requestDatagram.senderPort()+"]"
           +"req:"+request+",rsp:"+response;
    ui->listWidget->addItem(log);


}

QString Widget::process(const QString& request)
{
    return request;
}

